package com.lincoln.framework.utils;

import com.lincoln.framework.exception.ClientException;
import io.rong.RongCloud;
import io.rong.models.SMSSendCodeResult;
import io.rong.models.SMSVerifyCodeResult;

import java.util.HashMap;
import java.util.Map;

/**
 * 短信工具类
 * 
 * @author zwm
 * @version 2011-8-30 下午05:03:41
 */
public class SMSUtils {

	/** 日志 */
	private static FrameworkLogger logger = FrameworkLogger.initFrameworkLogger(SMSUtils.class);

	private static RongCloud rongCloud = RongCloud.getInstance("ConfigSetting.RY_APP_KEY", "ConfigSetting.RY_APP_SECRET");//文本内容在config.properties中设置,此项目未使用该工具

	/**
	 * 短信类型使用的模板
	 */
	private static Map<SMS_TYPE, String> smsTemplateIds = new HashMap<SMS_TYPE, String>() {
		{
			this.put(SMS_TYPE.COMMON, "4BTa8BZrQKo8D5swSJNDZN");
			this.put(SMS_TYPE.USER_VALIDATE, "aF4IcMK0k-NacrUEnJAvPB");
			this.put(SMS_TYPE.PASSWORD_MODIFY, "9fwvxuhA4-z9gJ2n_xK2JX");
			this.put(SMS_TYPE.PASSWORD_BACK, "bHpNCjfb4A5bGudwLl8Vbn");
			this.put(SMS_TYPE.REGIST, "7kGWyJZs4-0bEShGJVIfy1");
		}
	};

	public static enum SMS_TYPE {
		/**
		 * 注册
		 */
		REGIST,
		/**
		 * 密码找回
		 */
		PASSWORD_BACK,
		/**
		 * 修改密码
		 */
		PASSWORD_MODIFY,

		/**
		 * 身份验证
		 */
		USER_VALIDATE,
		/**
		 * 通用验证码
		 */
		COMMON
	}

	/**
	 * 发送短信
	 *
	 * @param mobile
	 * @param type
	 * @return sessionId 验证码，用于后续校验验证码 {@link SMSUtils#validateCode}
	 * @throws Exception
	 */
	public static String sendMessage(String mobile, SMS_TYPE type) throws Exception {
		logger.log("发送短信：【" + mobile + "】模板id【" + smsTemplateIds.get(type) + "】");
		SMSSendCodeResult result = rongCloud.sms.sendCode(mobile, smsTemplateIds.get(type), "86", null, null);
		logger.log("短信校验：" + result.toString());
		if (result.getCode() == 200) {
			return result.getSessionId();
		}
		throw new ClientException("发送短信失败：【" + result.getCode() + "】" + result.getErrorMessage());
	}

	/**
	 * 校验验证码是否正确
	 *
	 * @param sessionId
	 * @param code
	 * @return
	 * @throws Exception
	 */
	public static boolean validateCode(String sessionId, String code) throws Exception {
		SMSVerifyCodeResult codeResult = rongCloud.sms.verifyCode(sessionId, code);
		logger.log("短信验证码校验：" + codeResult.toString());
		return codeResult.getSuccess();
	}

}
